%% Optimal Deposit Insurance (Davila/Goldstein) -- 2022/10/24
run scripts/start_deposit;

% Parameters depositors
gam    = 1.5;  % 1/EIS
lambda = 0.05; % Fraction early depositors
prob   = 0.3;  % Sunspot (pi in paper)

% Deposit distribution
muD   = -3.8;
sigD  = 2.2;
d_min = 0.01;
d_max = 15; % Maximum deposit account (should be an even number)

% Endowments early and late depositors
y1 = 3;    % Share of outside income relative to deposits (early types)
y2 = 3.13; % Share of outside income relative to deposits (late types) (modulates R1)

% Banks
muS   = 0.08;
sigS  = 0.033; % high sigS, low elasticity
s_min = 1;     % Controls the probability of unique fundamental failure
s_max = 1.35;

phi     = 0.25; % Slope of rho1(s)
chi_avg = 0.72; % See chi calibrated below

% Taxpayers
kappa = [0.13,5.5]; % [kappa_1, kappa_2]

d_spc = 0.01; % 0.1; % Spacing grid of deposits
[dist_s, dist_d, d_grid] = build_distributions(muS,sigS,s_min,s_max,muD,sigD,d_min,d_max,d_spc,optfig,0);

ref_tax = 0.975;
chi   = fn_chi_calibration(chi_avg, s_min, s_max, dist_s);
Y1tau = (y1+1)*dist_d.icdf(ref_tax); % Outside income

% Build reference percentiles
percentiles    = [0.25, 0.75, 0.9, 0.95, 0.9999]'; % It should be odd
[D0i_grid, Di] = ref_percentiles(percentiles,dist_d,d_grid);
D0             = dist_d.mean; % Average deposit holdings

R1 = 1.02;
print_parameters;

benchmark(D0i_grid(1),lambda,gam,s_min,s_max,dist_s,phi,y1,y2,optfig) % Benchmark no runs/DI

% Grids
delta_grid_stp = 0.01;
delta_grid_max = 10; % Has to be less that R1*d_max
delta_grid     = (0:delta_grid_stp:delta_grid_max)';

%% Partial equilibrium
% 
R1_grid = (1.001:0.01:1.1)';
delta   = 1;
s       = dist_s.median;

environment(lambda,chi,phi,y1,y2,D0,R1,delta,delta_grid,dist_d,d_min,d_max,R1_grid,D0i_grid,s,optfig);
s_functions(prob,lambda,D0,chi,phi,R1,delta,dist_s,s_min,s_max,dist_d,d_min,d_max,R1_grid,delta_grid,optfig);

clear R1_grid delta s

%% Model Solution (fast)

[s_star, s_regions, s_hat, q_shat, q_sstar, q_F, dq_Fdd, ...
    T_star, T_smin, alpha_F_star, ...
    q_T, q_T_F, E_tax_F, E_tax_T_F, E_MC_tax_F, E_MC_tax_T_F, max_MC_tax,...
    Cdif, Cdif_i, Cdif_i_early, Cdif_i_late, Cdif_dep, Cdif_tax, ...
    MC_app0, MC_app0_i, MC_app0_i_early, MC_app0_i_late, MC_app0_dep, MC_app0_tax, ...
    MB_app0, MB_app0_i, MB_app0_i_early, MB_app0_i_late, MB_app0_dep, MB_app0_tax, ...
    dWdd_app0, dWdd_app0_i, dWdd_app0_i_early, dWdd_app0_i_late, dWdd_app0_dep, dWdd_app0_tax, ...
    W_app0, ind_max_W_app0] ...
    = fn_model_solution_app0(delta_grid, D0i_grid, R1, lambda, s_min, s_max, D0, prob, dist_s, dist_d, d_min, ...
    d_max, delta_grid_stp, chi, phi, gam, kappa, y1, y2, Y1tau);

save saved_data\welf_app0.mat; toc;

analysis_model;
